
#include <chrono>
#include <iostream>


using namespace std;
using namespace chrono;
template<class Duration>
using TimePoint = chrono::time_point<high_resolution_clock, Duration>;


void f()
{
    using namespace std;
    cout << "print 1000 stars ...." << endl;
    for (int i = 0; i < 1000; ++i)
    {
        cout << "*";
    }
    cout << endl;
}


int main()
{
    auto t1 = steady_clock::now();
    f();
    auto t2 = steady_clock::now();

    // 整数时长：时钟周期纳秒转毫秒，要求 duration_cast
    auto int_ms = duration_cast<chrono::milliseconds>(t2 - t1);

    // 小数时长：不要求 duration_cast
    duration<double, ratio<1, 1000>> fp_ms = t2 - t1;

    cout << "f() took " << fp_ms.count() << " ms, "
        << "or " << int_ms.count() << " whole milliseconds\n";


    TimePoint<seconds> time_point_sec(seconds(6));
    // 无精度损失, 可以进行隐式类型转换
    TimePoint<milliseconds> time_point_ms(time_point_sec);
    std::cout << time_point_ms.time_since_epoch().count() << " ms\n";    // 6000 ms

    time_point_ms = TimePoint<milliseconds>(milliseconds(6789));
    // error，会损失精度，不允许进行隐式的类型转换
    //TimePoint<Sec> sec(time_point_ms);

    // 显示类型转换,会损失精度。6789 truncated to 6000
    time_point_sec = time_point_cast<seconds>(time_point_ms);
    std::cout << time_point_sec.time_since_epoch().count() << " ms\n"; // 6000 ms
}

// 作者: 苏丙榅
// 链接: https://subingwen.cn/cpp/chrono/
// 来源: 爱编程的大丙
// 著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。